/* eslint-disable max-lines */
/* eslint-disable react/jsx-closing-tag-location */
import DrawerFooter from '@/components/DrawerFooter';
import { useStore } from '@/hooks';
import { Button, Dialog, Form, ResponsiveGrid, Tab, Icon, Input, Checkbox, Notification, Switch, NumberPicker, Message } from '@alifd/next';
import { t } from '@lingui/macro';
import React, { useEffect, useRef, useState } from 'react';
import { FieldsGrid, TitleGrid, orderModel, column, DATETIME_TEXT } from '../../stores/definitions_refund';
import { observer } from 'mobx-react-lite';
import { toJS, observable } from 'mobx';
import AttachmentForm from '../AttachmentForm';
import TauTable from '@/components/TauTable';
import UploadPanel from '@/components/UploadPanel';
import { uniqueId } from 'lodash';
import moment from 'moment';
import { verifyTicketPrice, verifyAccount, currentEditAccount, verifyAccountTotal, refundCaution, currentIsEdit, currentIsEditPS, computePrice } from '../../stores/method';

const FromItem = Form.Item;
const { Cell } = ResponsiveGrid;

const tabItems = [
  { key: '0', label: t`退票` },
  { key: '1', label: t`其他退款` },
  { key: '2', label: t`追加退款` },
];

const tabContent = {
  0: [
    'price', 'actualPrice', 'discountPrice', 'cancelTime', 'enableProfitShare', 'refundPrice', 'distanceTime', 'cancelRemark',
  ],
  1: [
    'price', 'actualPrice', 'discountPrice', 'cancelTime', 'refundPrice', 'enableProfitShare', 'cancelRemark',
  ],
  2: [
    'price', 'actualPrice', 'discountPrice', 'refundPrice', 'cancelRemark',
  ],
};

/**
 * 将改签车票赋值到老订单中
 * @param {*} tickets
 * @returns
 */
function mergeTicket(tickets) {
  // 订单中全部车票
  const rootTicket = tickets.filter((p) => !p.changeAssociatedOrderIds)[0].busOrder.orderDetails;
  const sortOrders = tickets.filter((p) => p.changeAssociatedOrderIds).sort((a, b) => b.changeBatch - a.changeBatch);
  const ticketMap = new Map();
  for (const item of sortOrders) {
    const { orderDetails } = item.busOrder;
    for (const ticket of orderDetails) {
      ticketMap.set(ticket.ticketCode, ticket);
    }
  }

  const updateTicket = rootTicket.map((p) => {
    if (ticketMap.has(p.ticketCode)) {
      return ticketMap.get(p.ticketCode);
    }
    return p;
  });
  return updateTicket;
}

const tableId = uniqueId('tauTable-');

const subModal = orderModel.busOrder.orderDetails;

function OrderRefund({ orderId, changeAssociatedOrderIds: ids, modal, onSubmit, onCancel, isEdit, onEdit, frequency }) {
  const { busOrderStore: store } = useStore();
  const [orderDetails, setOrderDetails] = useState([]); // 车票信息
  const [initOtherAccounts, setInitOtherAccounts] = useState([]); // 其他分账方信息
  const [accountSp, setAccountSp] = useState([]); // 其他分账方信息
  const [accountTotal, setAccountTotal] = useState([]); // 分账方汇总信息
  const editCtx = useRef({ origin: {}, changed: {} }).current; // 用于计算是否修改
  const [orderRefund] = useState(() => observable({}));
  const [tabIndex, setTabIndex] = useState('0'); // tab索引是否可控
  const [ticketRefund, setTicketRefund] = useState({}); // 车票已经退款信息
  const [enableProfitShare, setEnableProfitShare] = useState(false); // 订单是否已经开启分账
  const [refundInfos, setRefundInfos] = useState({}); // 订单退款信息
  const [isAccountTotalReady, setIsAccountTotalReady] = useState(false);
  const [ticketRefundPrices, setTicketRefundPrices] = useState({}); // 枚举出订单可以退款的金额
  const [refundTicketCode, setRefundTicketCode] = useState({}); // 枚举出全部已退款车票信息
  const [orderDiscountInfos, setOrderDiscountInfos] = useState({}); // 枚举出全部已退款车票信息

  // 是否第一页
  const type = toJS(store._orderRefundStatus) === '0';
  // 是否是编辑
  const edit = isEdit === 1;

  useEffect(() => { if (modal[1]?.startsWith?.('toClose')) handleCancel(); }, [modal]);
  useEffect(() => {
    (async () => {
      if (JSON.stringify(orderId) !== undefined) {
        if (edit) {
          const refundInfo = orderId;
          const { ticketRefundInfos = [] } = refundInfo;
          // const refundTicket = await store.getOrderRefundTicket({ applicationId, orderId: refundInfo.orderInfo.orderId });
          const orderInfo = await store.get(orderId.orderInfo.orderId);
          const ticketAmount = await store.getTicketRefunds(orderId.orderInfo.orderId);
          const refunds = await store.getRefund(orderId.orderInfo.orderId);
          // 订单优惠价格信息
          const discountInfo = await store.getOrderDiscountInfo({ orderId: orderId.orderInfo.orderId });
          setOrderDiscountInfos(discountInfo);
          if (JSON.stringify(refunds) !== '[]') {
            const filterRefunds = refunds?.filter((p) => p.ticketRefundInfos);
            const filteredArray = filterRefunds?.ticketRefundInfos?.filter((item) => item.firstChangePrice && (item.firstChangePrice > 0));
            const object = filteredArray?.reduce((acc, currentValue) => {
              acc[currentValue.ticketCode] = true;
              return acc;
            }, {});
            setRefundInfos(object);
          }
          const newDetail = orderInfo.busOrder.orderDetails.filter((p) => p.state !== '6').map((item) => {
            // 在 tickets 数组中查找与 detail 中当前元素相关联的数据
            const ticket = ticketRefundInfos?.find((ticketItem) => (ticketItem?.ticketCode === item?.ticketCode) && (ticketItem.isReturn === item.isReturn));
            if (ticket) {
              item.refundPrice = ticket.refundPrice;
              item.operatorRefundPrice = ticket?.operatorRefundPrice || 0;
              item.check = true;
              item.busTicketType;
              item.serviceCharge = ticket.serviceCharge;
              // item.editChangePrice = (ticketAmount[ticket.ticketCode] || 0) - ticket.refundPrice;
            }
            return item;
          });
          cmpTicketAmount(ticketAmount, newDetail);
          // 需要合并数据  把真实退款金额放上去
          const costOrderDetail = newDetail.map((p) => {
            const findIdx = discountInfo.find((j) => j.ticketCode === p.ticketCode);
            if (findIdx) {
              p.firstChangePrice = findIdx.discountPrice;
              p.costPrice = findIdx.costPrice;
              p.ticketCode = findIdx.ticketCode;
            }
            return p;
          });
          setOrderDetails(costOrderDetail);

          // 计算每一张车票可退金额金额 计算分帐法方金额会用到
          const refundPrices = orderInfo?.busOrder?.orderDetails?.reduce((obj, item) => {
            const { ticketCode, price, isReturn } = item;
            if (isReturn === '0') {
              obj[ticketCode] = price;
            }
            return obj;
          }, {});
          setTicketRefundPrices(refundPrices);

          // 赋值出发时间
          refundInfo.busOrder = {
            shift: {
              date: orderInfo.busOrder.shift.date,
            },
          };
          const checkTicket = refundInfo?.ticketRefundInfos?.map((item) => ({
            ...item,
            check: true,
          }));
          // 计算优惠券成本
          const { discountInfos = [] } = orderInfo;
          let preferentialCost = 0;
          for (const item of discountInfos) {
            const { cost = 0 } = item;
            preferentialCost += cost;
          }
          _.set(refundInfo, 'cancelTime', DATETIME_TEXT(refundInfo.cancelTime));
          _.set(refundInfo, 'enableProfitShare', orderInfo.enableProfitShare);
          _.set(orderRefund, 'discountPrice', `${(orderInfo?.originalPrice - (orderInfo?.price || 0)).toFixed(2)} / ${preferentialCost.toFixed(2)}`);
          _.set(orderRefund, 'actualPrice', orderInfo?.price?.toFixed(2) || 0);
          _.set(orderRefund, 'price', orderInfo?.originalPrice?.toFixed(2) || 0);
          _.assign(orderRefund, refundInfo);
          _.assign(orderRefund, { orderDetails: checkTicket });
          // 初始化分账金额
          const initOtherAccount = refundInfo?.refundPayers?.map((item) => ({
            ...item,
            pendingSettlementAmount: (item.pendingSettlementAmount / 100).toFixed(2),
            contributionAmount: (item.contributionAmount / 100).toFixed(2),
          }));
          store.initAccounts = initOtherAccount;
          store.accounts = refundInfo?.refundPayers;
          setAccountTotal(initOtherAccount);
          setInitOtherAccounts(initOtherAccount);
          setEnableProfitShare(orderInfo?.enableProfitShare);
          editCtx.origin = _.cloneDeep(refundInfo);
        } else {
          const refundInfo = await store.get(orderId);
          const { extras } = await store.getDictItem('offlinePay', 'company');
          const { changeAssociatedOrderIds, busOrder } = refundInfo;
          let orderRoot = null;
          let detail = busOrder.orderDetails;
          if (ids) {
            const orderIds = await store.getChangeOrder([...ids]);
            orderRoot = orderIds.filter((p) => !p.changeAssociatedOrderIds)[0];
            detail = mergeTicket(orderIds);
          }
          const id = changeAssociatedOrderIds ? orderRoot.id : orderId;
          const res = await store.getAccount(id);
          const ticketAmount = await store.getTicketRefunds(id);
          const refunds = await store.getRefund(id);
          // 订单优惠价格信息
          const discountInfo = await store.getOrderDiscountInfo({ orderId: id });
          setOrderDiscountInfos(discountInfo);
          if (JSON.stringify(refunds) !== '[]') {
            const filteredArray = refunds[0]?.ticketRefundInfos?.filter((item) => item.firstChangePrice && (item.firstChangePrice > 0));
            const object = filteredArray.reduce((acc, currentValue) => {
              acc[currentValue.ticketCode] = true;
              return acc;
            }, {});
            setRefundInfos(object);
          }
          // 过滤掉state为-1的主数据 且过滤其他退款不存在ticketRefundInfos的数据
          const filteredData = refunds.filter((item) => item.state !== '-1' && item.ticketRefundInfos);
          const result = {};
          // 遍历过滤后的主数组
          filteredData.forEach((item) => {
            // 遍历每个对象中的ticketRefundInfos数组
            item.ticketRefundInfos.forEach((p) => {
              // 将ticketCode作为键，整个p对象作为值添加到result对象中
              result[p.ticketCode] = p;
            });
          });
          setRefundTicketCode(result);

          const isRefund = refundInfo.applicationRefunds
            ?.filter((item) => item.type === '0');
          // 包含的是两张后端返回的车票
          // eslint-disable-next-line @iceworks/best-practices/recommend-polyfill
          const tickets = isRefund?.flatMap((item) => item.ticketRefundInfos);

          // 创建一个基准数据的映射，方便根据 ticketCode + isReturn 查找
          const baseOrderDetailsMap = new Map();
          detail.forEach((item) => {
            const key = item.ticketCode + item.isReturn;
            baseOrderDetailsMap.set(key, { ...item, isModified: false });
          });

          // 遍历所有车票并设置 isModified 标识
          detail.forEach((item) => {
            const key = item.ticketCode + item.isReturn;
            if (item.originalTicketCode) {
              // 如果包含 originalTicketCode，将 isModified 设为 true
              if (baseOrderDetailsMap.has(key)) {
                baseOrderDetailsMap.set(key, { ...item, isModified: true });
              }

              // 查找同一 ticketGroup 的其他车票并标记为已改签
              const { ticketGroup } = item;
              baseOrderDetailsMap.forEach((p, detailKey) => {
                if (p.ticketGroup === ticketGroup && !p.isModified) {
                  p.isModified = true;
                  baseOrderDetailsMap.set(detailKey, p);
                }
              });
            }
          });

          // 将最终结果转换为数组
          const tmpDetail = Array.from(baseOrderDetailsMap.values());

          const newDetail = tmpDetail.map((item) => {
            // 在 tickets 数组中查找与 detail 中当前元素相关联的数据
            const ticket = tickets?.find((ticketItem) => (ticketItem?.ticketCode === item?.ticketCode) && (ticketItem.isReturn === item.isReturn));
            if (ticket) {
              item.operatorRefundPrice = (ticket?.operatorRefundPrice || 0).toFixed(2);
              item.busTicketType;
            }
            return item;
          });

          // 需要合并数据  把真实退款金额放上去
          const costOrderDetail = newDetail.map((p) => {
            const findIdx = discountInfo.find((j) => (j.ticketCode === p.ticketCode) && (j.isReturn === p.isReturn));
            if (findIdx) {
              // eslint-disable-next-line no-param-reassign
              p = { ...p, ...findIdx };
            }
            return p;
          });
          setOrderDetails([...costOrderDetail]); // 车票信息

          // 每张车票分帐方可退金额  计算分帐方会使用到
          const refundPrices = refundInfo?.busOrder?.orderDetails?.reduce((obj, item) => {
            const { ticketCode, price, isReturn } = item;
            if (isReturn === '0') {
              obj[ticketCode] = price;
            }
            return obj;
          }, {});
          setTicketRefundPrices(refundPrices);

          // 初始化分账金额
          const initOtherAccount = res?.map((item) => ({
            ...item,
            pendingSettlementAmount: ((item.pendingSettlementAmount - item.refundedAmount) / 100).toFixed(2),
          }));

          setAccountSp(initOtherAccount);
          if (!initOtherAccount.some((p) => p.targetId === extras['兜底公司']?.value || p.targetId === 'PLATFORM')) {
            const _supplement = [...initOtherAccount, { targetName: t`平台`, targetId: 'PLATFORM', targetType: 'PLATFORM', pendingSettlementAmount: 0, contributionAmount: 0 }];
            setAccountSp(_supplement);
          }

          const diff = moment.duration(moment(refundInfo.busOrder.shift.date).diff(moment()));
          const diffStr = `${Math.floor(diff.asHours())}小时${diff.minutes()}分钟${diff.seconds()}秒`;
          store.initAccounts = initOtherAccount;
          store.accounts = res;
          // 计算优惠券成本
          const { discountInfos = [] } = refundInfo;
          let preferentialCost = 0;
          for (const item of discountInfos) {
            const { cost = 0 } = item;
            preferentialCost += cost;
          }
          setTicketRefund(ticketAmount);
          setAccountTotal(initOtherAccount);
          setInitOtherAccounts(initOtherAccount);
          editCtx.origin = _.cloneDeep(refundInfo);
          _.assign(orderRefund, { orderDetails: costOrderDetail });
          _.assign(orderRefund, refundInfo);
          _.set(orderRefund, 'refundPrice', '0');
          _.set(orderRefund, 'cancelTime', moment().format('YYYY-MM-DD HH:mm:ss'));
          _.set(orderRefund, 'distanceTime', diffStr);
          _.set(orderRefund, 'cancelCoupon', true);
          _.set(orderRefund, 'enableProfitShare', refundInfo?.enableProfitShare || false);
          _.set(orderRefund, 'discountPrice', `${(refundInfo?.originalPrice - (refundInfo?.price || 0)).toFixed(2)} / ${preferentialCost.toFixed(2)}`);
          _.set(orderRefund, 'actualPrice', refundInfo?.price?.toFixed(2) || 0);
          _.set(orderRefund, 'price', refundInfo?.originalPrice?.toFixed(2) || 0);
          setEnableProfitShare(refundInfo?.enableProfitShare);
        }
      }
    })();
    return () => {
      store._orderRefundStatus = '0';
    };
  }, []);

  function cmpTicketAmount(obj, arr) {
    // 遍历对象并生成新对象
    const newObj = {};
    for (const key in obj) {
      // eslint-disable-next-line @iceworks/best-practices/recommend-polyfill, no-prototype-builtins
      if (obj.hasOwnProperty(key)) {
        // 查找数组中的对应项
        const foundItem = arr.find((item) => item.ticketCode === key);

        if (foundItem) {
          // 用对象的值减去数组中的值，并存储到新对象中
          newObj[key] = obj[key] - foundItem.refundPrice;
        } else {
          // 如果在数组中未找到对应项，直接将原对象的值存储到新对象中
          newObj[key] = obj[key];
        }
      }
    }
    setTicketRefund(newObj); // 需要计算已经退了多少
  }

  useEffect(() => {
    if (orderId?.type === '2') {
      setTabIndex('1');
      store._orderRefundStatus = '1';
    } else if (orderRefund?.busOrder?.orderStatus === 2) {
      store._orderRefundStatus = '1';
    } else {
      store._orderRefundStatus = '0';
      setTabIndex('0');
    }
  }, []);

  useEffect(() => {
    if (accountTotal && accountTotal.length > 0) {
      setIsAccountTotalReady(true);
    }
  }, [accountTotal]);

  useEffect(() => {
    // 车票退款
    if (tabIndex === '0') {
      const prices = orderDetails.filter((item) => !item.disabled).map((item) => item.refundPrice).filter((item) => item);
      let priceSum = 0; // 退款总金额
      prices.forEach((item) => {
        priceSum += (item ? Number(item) : 0);
      });
      _.set(orderRefund, 'refundPrice', priceSum.toFixed(2));
      // 不存在分帐方会报错
      if (!isEdit && accountTotal.length > 0) {
        // 需要勾选后默认给出全部可退金额
        const cloneDetails = _.cloneDeep(orderDetails);
        const cloneAccount = _.cloneDeep(accountTotal);
        const operationAmount = cloneDetails.filter((p) => p.check).filter((p) => p.isReturn === '0').reduce((acc, item) => {
          const price = ticketRefundPrices[item.ticketCode];
          acc += price;
          return acc;
        }, 0);
        // 如果是正常退款
        // 先查找到中港通那边的索引  然后需要计算中港通该出多少钱
        // 只要退款合伙人必出
        const operationIndex = cloneAccount.findIndex((p) => p.targetType === 'OPERATION'); // 中港通
        const platFormIndex = cloneAccount.findIndex((p) => p.targetType === 'PLATFORM'); // 平台
        const partnerIndex = cloneAccount.findIndex((p) => p.targetType === 'PARTNER'); // 合伙人
        const individual = cloneAccount.findIndex((p) => p.targetType === 'INDIVIDUAL'); // 平台分润
        const manager = cloneAccount.findIndex((p) => p.targetType === 'MANAGER'); // 客户经理
        const isOperation = operationIndex >= 0;
        const isPartner = partnerIndex >= 0;
        const isPlatform = platFormIndex >= 0;
        const isIndividual = individual >= 0;
        const isManager = manager >= 0;

        // 如果存在平台分润或者客户经理  默认出全款
        if (isIndividual) {
          cloneAccount[individual].contributionAmount = operationAmount === 0 ? (0).toFixed(2) : cloneAccount[individual].pendingSettlementAmount;
        }
        if (isManager) {
          cloneAccount[manager].contributionAmount = operationAmount === 0 ? (0).toFixed(2) : cloneAccount[manager].pendingSettlementAmount;
        }

        // 出资金额减去每张车票中港通可出金额汇总  还需考虑是否够出
        const operationPendingAmount = Number(cloneAccount[operationIndex]?.pendingSettlementAmount)?.toFixed(2);

        isPartner && (cloneAccount[partnerIndex].contributionAmount = Number(cloneAccount[partnerIndex]?.pendingSettlementAmount)?.toFixed(2));
        // 如果中港通够出  出资金额就等于车票金额汇总
        if (operationPendingAmount >= operationAmount) {
          isOperation && (cloneAccount[operationIndex].contributionAmount = operationAmount.toFixed(2));
        } else {
          // 如果不够出  那就给全部待分帐金额  多余出资金额就放在平台那边 还需要减去合伙人
          isOperation && (cloneAccount[operationIndex].contributionAmount = Number(cloneAccount[operationIndex]?.pendingSettlementAmount)?.toFixed(2));
          isPlatform && (cloneAccount[platFormIndex].contributionAmount = operationPendingAmount - operationAmount - (isIndividual ? cloneAccount[individual].pendingSettlementAmount : 0) - (isPartner ? Number(cloneAccount[partnerIndex]?.pendingSettlementAmount) : 0) - (isManager ? cloneAccount[manager].pendingSettlementAmount : 0).toFixed(2));
        }
        // 还需计算退款金额和分帐方是否相等  不等的话还需要做其他逻辑 如果是平台金额高
        if (priceSum > operationAmount) {
          isPlatform && (cloneAccount[platFormIndex].contributionAmount = (priceSum - operationAmount - (isPartner ? Number(cloneAccount[partnerIndex]?.pendingSettlementAmount) : 0) - (isIndividual ? Number(cloneAccount[individual].pendingSettlementAmount) : 0) - (isManager ? cloneAccount[manager].pendingSettlementAmount : 0)).toFixed(2));
        } else {
          // 如果是出资金额大于退款金额
          isPlatform && (cloneAccount[platFormIndex].contributionAmount = 0);
        }
        setAccountTotal(cloneAccount);
      } else {
        // 手动计算
      }
    } else if (tabIndex === '1') {
      // 其他退款
      _.set(orderRefund, 'refundPrice', orderId?.refundPrice);
    }
  }, [orderDetails, isAccountTotalReady]);

  const handleChange = (values, item) => {
    const { name, value } = item;
    _.set(orderRefund, name, value);
    if (name === 'cancelTime') {
      const diff = moment.duration(moment(orderRefund.busOrder.shift.date).diff(moment(value)));
      const diffStr = `${Math.floor(diff.asHours())}小时${diff.minutes()}分钟${diff.seconds()}秒`;
      _.set(orderRefund, 'distanceTime', diffStr);
    }
    // eslint-disable-next-line eqeqeq
    editCtx.changed[name] = value == _.get(editCtx.origin, name) ? undefined : value;
  };

  const overrideModel = {
    enableProfitShare: {
      label: '是否开启分账',
      ui: {
        renderer: (v) => <Switch disabled={enableProfitShare} checked={v} unCheckedChildren="否" checkedChildren="是" autoWidth />,
      },
    },
    discountPrice: {
      label: t`券面值/第三方价格`,
    },
    refundPrice: {
      label: '退款金额',
      ui: {
        renderer: (v) => (store._orderRefundStatus !== '1' ? <span>{v}</span> : <Input value={v} />),
        itemProps: { required: store._orderRefundStatus === '1' },
      },
    },
  };

  const handleCancel = () => {
    // eslint-disable-next-line no-return-assign, no-param-reassign
    if (!_.isEmpty(_.transform(editCtx.changed, (r, v, k) => v !== undefined && (r[k] = v)))) {
      Dialog.confirm({
        content: t`放弃修改内容？`,
        onOk: () => onCancel?.(),
      });
      return;
    }
    onCancel?.();
  };

  // 提交
  const handleSubmit = (__, errors, ___) => {
    if (!_.isEmpty(errors)) {
      console.log('🚀 _ file: RefundPrice.jsx:471 _ errors:', errors);
      return;
    }
    const { _orderRefundStatus, accounts, initAccounts } = store;
    if (_orderRefundStatus === '2' && orderRefund.refundPrice === '0') {
      return refundCaution();
    }
    let verifyPrice;
    let verifyInitAccount;
    if (_orderRefundStatus !== '2') {
      verifyPrice = verifyAccount(_orderRefundStatus, _orderRefundStatus == '0' ? accountTotal : initOtherAccounts, initOtherAccounts, toJS(orderRefund));
      verifyInitAccount = verifyAccountTotal(store.accounts, _orderRefundStatus === '0' ? accountTotal : initOtherAccounts);
    }
    if (verifyPrice || verifyInitAccount) {
      return;
    }
    let refundType = '';
    if (Number(_orderRefundStatus) === 0) {
      refundType = '0';
    } else {
      refundType = '2';
    }
    // 如果是已完成订单
    if (orderRefund?.busOrder?.orderStatus === 2) {
      refundType = '2';
    }
    // 这个成本价总和需要根据后端返回的数据进行计算
    const costTotalAmount = orderDiscountInfos.reduce((acc, item) => {
      const { costPrice } = item;
      acc += costPrice;
      return acc;
    }, 0);
    const { refundPrice } = toJS(orderRefund);
    // 退款总额不可大于出资金额
    if (_orderRefundStatus !== '2' && (refundPrice > costTotalAmount)) {
      return Notification.open({
        title: '警告⚠️',
        content:
          '退款总和不可大于订单价格',
        type: 'warning',
      });
    }
    const prices = computePrice({ order: orderRefund, refundPrice: Number(refundPrice) });
    const { otherPrice, platformPrice } = prices;
    if (store._orderRefundStatus !== '2') {
      Dialog.confirm({
        title: t`退款是否提交财务`,
        content: (<div>
          {(platformPrice !== null) && <span>{t`平台退款: ${platformPrice.toFixed(2)} 元`}</span>}
          <br />
          {(otherPrice !== null) && <span>{t`第三方退款: ${otherPrice.toFixed(2)} 元`}</span>}
        </div>),
        onOk: () => {
          onSubmit?.(orderRefund, '2', refundType, accountTotal, initOtherAccounts, store._orderRefundStatus, enableProfitShare, accounts, initAccounts);
        },
        onCancel: () => onSubmit?.(orderRefund, '1', refundType, accountTotal, initOtherAccounts, store._orderRefundStatus, enableProfitShare, accounts, initAccounts),
        okProps: {
          children: '是', // 设置确定按钮的文本
        },
        cancelProps: {
          children: '否', // 设置取消按钮的文本
        },
      });
    } else {
      if (!accountSp.some((p) => p.check)) {
        Message.error({ content: t`请选择分账方` });
        return;
      }
      Dialog.confirm({
        title: t`退款是否提交财务`,
        content: (<div>
          {(platformPrice !== null) && <span>{t`平台退款: ${platformPrice.toFixed(2)} 元`}</span>}
          <br />
          {(otherPrice !== null) && <span>{t`第三方退款: ${otherPrice.toFixed(2)} 元`}</span>}
        </div>),
        onOk: () => {
          onSubmit?.(orderRefund, '2', refundType, accountTotal, initOtherAccounts, store._orderRefundStatus, accountSp, enableProfitShare, accounts, initAccounts, accountSp);
        },
        okProps: {
          children: '是', // 设置确定按钮的文本
        },
      });
    }
  };

  // 编辑
  const handleEdit = (__, errors, ___) => {
    if (!_.isEmpty(errors)) {
      return;
    }
    const { _orderRefundStatus } = store;
    const { refundPrice } = toJS(orderRefund);
    if (_orderRefundStatus === '2' && orderRefund.refundPrice === '0') {
      return refundCaution();
    }
    let verifyPrice;
    let verifyInitAccount;
    if (_orderRefundStatus !== '2') {
      verifyPrice = verifyAccount(_orderRefundStatus, _orderRefundStatus == '0' ? accountTotal : initOtherAccounts, initOtherAccounts, toJS(orderRefund));
      verifyInitAccount = verifyAccountTotal(store.accounts, _orderRefundStatus === '0' ? accountTotal : initOtherAccounts);
    }
    if (verifyPrice || verifyInitAccount) {
      return;
    }
    if (refundPrice === 0 || refundPrice === '0' || refundPrice === '') {
      return Notification.open({
        title: '警告⚠️',
        content:
          '退款金额不可为0',
        type: 'warning',
      });
    }
    // 这个成本价总和需要根据后端返回的数据进行计算
    const costTotalAmount = orderDiscountInfos.reduce((acc, item) => {
      const { costPrice } = item;
      acc += costPrice;
      return acc;
    }, 0);
    // 订单总额不可大于退款金额  在其他退款内
    if (refundPrice > costTotalAmount) {
      return Notification.open({
        title: '警告⚠️',
        content:
          '退款总和不可大于订单价格',
        type: 'warning',
      });
    }
    const prices = computePrice(orderRefund);
    const { otherPrice, platformPrice } = prices;
    Dialog.confirm({
      title: t`退款是否提交财务`,
      content: (<div>
        {(platformPrice !== null) && <span>{t`平台退款: ${Number(platformPrice).toFixed(2)} 元`}</span>}
        <br />
        {(otherPrice !== null) && <span>{t`第三方退款: ${Number(otherPrice).toFixed(2)} 元`}</span>}
      </div>),
      onOk: () => onEdit?.(orderRefund, store._orderRefundStatus, accountTotal, initOtherAccounts),
    });
  };

  // 勾选事件回调
  const handleCheckbox = (e, i, r) => {
    const deepCopyData = _.cloneDeep(orderDetails);
    deepCopyData[i].check = e;

    // 处理往返票情况  把对应的返程票也够选上
    deepCopyData.forEach((item, index) => {
      if (item.ticketGroup == r.ticketGroup) {
        item.check = e;
        deepCopyData[index].refundPrice = !e ? 0 : Number(deepCopyData[index].costPrice).toFixed(2);
        deepCopyData[index].serviceCharge = 0;
      } else {
        deepCopyData[i].refundPrice = !e ? 0 : Number(deepCopyData[index].costPrice).toFixed(2);
        deepCopyData[i].serviceCharge = 0;
      }
    });

    setOrderDetails(deepCopyData);
    _.assign(orderRefund, { orderDetails: deepCopyData });
  };

  // 记录输入的金额
  const handleChangeService = (v, r, i) => {
    if (v.split('.')[1]?.length > 2) {
      return;
    }
    const currentNext = verifyTicketPrice(ticketRefund, orderDetails, v, r);
    if (currentNext) {
      return;
    }
    // 直接改变原数据  记录下每张车票里面设置了多少退款金额
    orderDetails[i].serviceCharge = v;
    // 退款金额计算逻辑  订单价格 - 输入的手续费 - 已退金额 - 优惠金额
    orderDetails[i].refundPrice = (Number(orderDetails[i].costPrice) - Number(v)).toFixed(2);
    orderDetails[i].operatorRefundPrice = (Number(orderDetails[i].costPrice) - Number(v)).toFixed(2);
    if (edit) {
      orderRefund.ticketRefundInfos[i] = {
        serviceCharge: v,
      };
      orderRefund.ticketRefundInfos[i].refundPrice = Number(orderRefund.ticketRefundInfos[i].costPrice) - Number(v);
      orderRefund.ticketRefundInfos[i].operatorRefundPrice = (Number(orderRefund.ticketRefundInfos[i].costPrice) - Number(v)).toFixed(2);
    }
    const prices = orderDetails.filter((item) => !item.disabled).map((item) => item.refundPrice).filter((item) => item !== undefined);
    // 退款金额默
    let priceSum = 0;
    prices.forEach((item) => {
      priceSum += Number(item);
    });
    _.assign(orderRefund, { refundPrice: priceSum.toFixed(2) || 0, orderDetails });
    setOrderDetails([...orderDetails]);
  };

  /**
  * 分账方输入分账金额事件
  * @param {*} e
  * @param {*} r
  * @param {*} i
  */
  const handleRefundAccountPrice = (e, r, i) => {
    // 修改前校验是否修改过 出资金额
    if (currentIsEdit(accountTotal)) return;
    if (currentEditAccount(enableProfitShare)) return;
    setAccountTotal((pre) => {
      const res = [...pre];
      res[i].pendingSettlementAmount = e;
      return res;
    });
  };

  /**
  * 分账方汇总输入分账金额事件
  * @param {*} e
  * @param {*} r
  * @param {*} i
  */
  const handleAccountRefundPrice = (e, r, i) => {
    // 校验是否可以修改
    if (currentIsEditPS(store.initAccounts, accountTotal)) return;
    setAccountTotal((pre) => {
      const res = [...pre];
      res[i].contributionAmount = e;
      return res;
    });
  };

  /**
  * 其他分账方输入分账金额事件
  * @param {*} e
  * @param {*} r
  * @param {*} i
  */
  const handleOtherRefundAccountPrice = (e, r, i) => {
    // 修改前校验是否修改过 出资金额
    if (currentIsEdit(initOtherAccounts)) return;
    if (currentEditAccount(orderRefund?.enableProfitShare)) return;
    setInitOtherAccounts((pre) => {
      const res = [...pre];
      res[i].pendingSettlementAmount = e;
      return res;
    });
  };

  /**
   * 其他退款输入金额事件
   * @param {*} e
   * @param {*} v
   * @param {*} i
   */
  const handleOtherRefundPrice = (e, v, i) => {
    if (currentIsEditPS(store.initAccounts, initOtherAccounts)) return;
    setInitOtherAccounts((pre) => {
      const res = [...pre];
      res[i].contributionAmount = e;
      return res;
    });
  };

  /**
   * 是否由平台代付
   * @param {*} e
   * @param {*} i
   * @param {*} platType 区分退票和其他
   */
  const handleAccountPlat = (e, i, v, platType) => {
    if (platType === 'A') {
      setAccountTotal((pre) => {
        const res = [...pre];
        res[i].platformContribution = e;
        return res;
      });
    } else {
      setInitOtherAccounts((pre) => {
        const res = [...pre];
        res[i].platformContribution = e;
        return res;
      });
    }
  };

  /**
  * tab事件回调  是否允许切换tab
  * @param {*} v
  */
  const handleTabChange = (v) => {
    if (!edit) {
      store._orderRefundStatus = v;
    }
  };

  const handleSupplementCheck = (e, i) => {
    const temp = _.cloneDeep(accountSp);
    temp[i].check = e;
    setAccountSp(temp);
    calculateRefundPrice(temp);
  };

  const handleChangeAmountSp = (e, r, i) => {
    const temp = _.cloneDeep(accountSp);
    const value = e || 0;
    temp[i].contributionAmount = value;
    setAccountSp(temp);
    calculateRefundPrice(temp);
  };

  function calculateRefundPrice(data) {
    const temp = _.cloneDeep(data);
    let price = 0;
    for (let i = 0; i < temp.length; i++) {
      const { contributionAmount = 0, check = null } = temp[i];
      if (check) {
        price += Number(contributionAmount);
      }
    }
    _.set(orderRefund, 'refundPrice', price.toFixed(2));
  }

  return (
    <Form
      inline
      value={orderRefund}
      onChange={handleChange}
      useLabelForErrorMessage
    >
      <Tab
        // eslint-disable-next-line no-nested-ternary
        activeKey={edit ? tabIndex : (orderRefund?.busOrder?.orderStatus === 2 ? '1' : store._orderRefundStatus)}
        onChange={(v) => handleTabChange(v)}
      >
        {tabItems.map((item) => (<Tab.Item disabled={orderRefund?.busOrder?.orderStatus === 2} key={item.key} title={item.label} />))}
      </Tab>
      <TitleGrid title={t`基本信息`} />
      <FieldsGrid
        formData={orderRefund}
        mode={modal[0]}
        overrideModel={overrideModel}
        // eslint-disable-next-line no-nested-ternary
        columns={4}
        // eslint-disable-next-line no-nested-ternary
        fields={tabContent[edit ? tabIndex : (orderRefund?.busOrder?.orderStatus === 2 ? '1' : store._orderRefundStatus)]}
      />
      {
        // eslint-disable-next-line no-nested-ternary
        (edit ? orderRefund.type === '0' : (orderRefund?.busOrder?.orderStatus === 2 ? false : type)) && <TitleGrid title={t`车票信息`} />
      }
      {
        // eslint-disable-next-line no-nested-ternary
        (edit ? orderRefund.type === '0' : (orderRefund?.busOrder?.orderStatus === 2 ? false : type)) && <div className="content">
          <TauTable
            instanceId={tableId}
            tableLayout="fixed"
            hidePagination
            dataSource={orderDetails}
            rowKey="ticketCode" // 设置每行的唯一标识
            columns={[
              { title: t`序号`, dataIndex: 'idx', width: 44, cell: (v, i) => store.ticIdx(i) },
              column('ticketCode', { width: 88 }, subModal),
              column('ticketPrice', { width: 58 }, subModal),
              column('operatingState', { width: 88 }, subModal),
              column('state', { width: 78 }, subModal),
              column('shiftTime', { width: 78 }, subModal),
              column('firstChangePrice', {
                width: 58,
                cell: (v) => {
                  const value = Number(v) || 0;
                  return <span>{value?.toFixed(2)}</span>;
                },
              }, subModal),
              column('serviceCharge', {
                width: 58,
                cell: (v, i, r) => (
                  <>
                    {(r.ticketPrice == 0 || r?.disabled || !r?.check) ?
                      <span>{0}</span> :
                      <Input value={v} style={{ width: 70 }} onChange={(e) => handleChangeService(e, r, i)} />}
                  </>
                ),
              }, subModal),
              column('refundPrice', {
                width: 88,
                cell: (v) => {
                  const value = Number(v) || 0;
                  return <span>{value?.toFixed(2)}</span>;
                },
              }, subModal),
              {
                title: t`选择`,
                dataIndex: 'check',
                width: 50,
                cell: (text, i, refund) => {
                  return (
                    <Checkbox checked={text} disabled={refund.isModified || (refundTicketCode[refund.ticketCode] && JSON.stringify(refundTicketCode[refund.ticketCode]))} onChange={(e) => handleCheckbox(e, i, refund)} />
                  );
                },
              },
            ]}
          />
        </div>
      }
      {store._orderRefundStatus === '0' && <>
        <TitleGrid title={t`分账方金额汇总`} />
        <div>
          <p><b>{t`注意事项: 退款后此订单是否还保留该分帐方，在退款时，承运商的出资金额大于退款金额，剩余的出资金额会进入平台。`}</b></p>
        </div>
        <TauTable
          instanceId={tableId}
          tableLayout="fixed"
          hidePagination
          style={{ width: '100%' }}
          dataSource={accountTotal}
          rowKey="total" // 设置每行的唯一标识
          columns={[
            { title: t`序号`, dataIndex: 'idx', width: 44, cell: (v, i) => store.ticIdx(i) },
            column('targetName', { width: 100 }),
            column('pendingSettlementAmount', {
              width: 88,
              cell: (v, i, r) => (
                <>
                  <Input value={v} style={{ width: 80 }} onChange={(e) => handleRefundAccountPrice(e, r, i)} />
                </>
              ),
            }),
            column('contributionAmount', {
              width: 88,
              cell: (v, i, r) => (
                <>
                  <Input value={v} style={{ width: 80 }} onChange={(e) => handleAccountRefundPrice(e, r, i)} />
                </>
              ),
            }),
            {
              title: t`平台代付`,
              dataIndex: 'platformContribution',
              width: 50,
              cell: (text, i, refund) => (
                <Checkbox checked={text} disabled={!refund.settled} onChange={(e) => handleAccountPlat(e, i, refund, 'A')} />),
            },
          ]}
        />
      </>}
      {/* 适用于 其他退款 和追加付款 分账方 */}
      {(store._orderRefundStatus === '1') &&
        <>
          <TitleGrid title={t`分账方信息`} />
          <TauTable
            instanceId={tableId}
            tableLayout="fixed"
            hidePagination
            style={{ width: '100%' }}
            dataSource={initOtherAccounts}
            rowKey="otherAccount" // 设置每行的唯一标识
            columns={
              [
                { title: t`序号`, dataIndex: 'idx', width: 44, cell: (v, i) => store.ticIdx(i) },
                column('targetName', { width: 100 }),
                column('pendingSettlementAmount', {
                  width: 88,
                  cell: (v, i, r) => (
                    <>
                      <Input value={v} style={{ width: 80 }} onChange={(e) => handleOtherRefundAccountPrice(e, r, i)} />
                    </>
                  ),
                }),
                column('contributionAmount', {
                  width: 88,
                  cell: (v, i, r) => <Input value={v} style={{ width: 80 }} onChange={(e) => handleOtherRefundPrice(e, r, i)} />,
                }),
                {
                  title: t`平台代付`,
                  dataIndex: 'platformContribution',
                  width: 50,
                  cell: (text, i, refund) => (
                    <Checkbox checked={text} disabled={!refund.settled} onChange={(e) => handleAccountPlat(e, i, refund, 'other')} />),
                },
              ]}
          />
        </>
      }

      {(store._orderRefundStatus === '2') &&
        <>
          <TitleGrid title={t`分账方信息`} />
          <TauTable
            instanceId={tableId}
            tableLayout="fixed"
            hidePagination
            style={{ width: '100%' }}
            dataSource={accountSp}
            rowKey="otherAccount" // 设置每行的唯一标识
            columns={
              [
                { title: t`序号`, dataIndex: 'idx', width: 44, cell: (v, i) => store.ticIdx(i) },
                column('targetName', {
                  width: 100,
                  cell: (v, i, r) => {
                    const { targetName, targetId } = r || {};
                    return (
                      <>
                        <div>{targetName}</div>
                        <div style={{ color: '#999' }}>{targetId}</div>
                      </>
                    );
                  },
                }),
                column('pendingSettlementAmount', {
                  width: 88,
                }),
                column('contributionAmount', {
                  width: 88,
                  cell: (v, i, r) => (r.check ? <NumberPicker precision={2} value={v} style={{ width: 80 }} onChange={(e) => handleChangeAmountSp(e, r, i)} /> : <>{v}</>),
                }),
                {
                  title: t`选择`,
                  dataIndex: 'check',
                  width: 50,
                  cell: (v, i, refund) => (
                    <Checkbox checked={v} onChange={(e) => handleSupplementCheck(e, i, refund)} />),
                },
              ]}
          />
        </>
      }

      <AttachmentPanel refund={orderRefund} mode={modal[0]} />

      <DrawerFooter>
        <FromItem>
          <Form.Submit validate type="primary" onClick={edit ? handleEdit : handleSubmit}>{edit ? t`修改` : t`保存`}</Form.Submit>
          <Button style={{ marginLeft: 8 }} onClick={handleCancel}>{t`取消`}</Button>
        </FromItem>
      </DrawerFooter>
    </Form>
  );
}

const AttachmentPanel = observer(({ refund, mode }) => {
  const [curAttachment, setCurAttachment] = useState();
  const [idx, setIdx] = useState(-1); // 当前选中的附件
  const isViewMode = mode === 'check';

  useEffect(() => {
    if (refund?.attachments?.length) setIdx(0);
  }, [refund?.attachments]);

  const handleAddAttachment = () => {
    if (!refund?.attachments) refund.attachments = [];
    refund.attachments.push({ title: t`附件`, description: t`附件说明`, binaryId: [] });
    setIdx(refund.attachments.length - 1);
  };

  const handleDeleteAttachment = (i, e) => {
    refund.attachments.splice(i, 1);
    if (i === idx) setIdx(i - 1);
    e.preventDefault();
    e.stopPropagation();
  };

  return (
    <>
      <TitleGrid title={<span>{t`附件`}{mode !== 'view' && <Button type="primary" style={{ marginLeft: 24 }} onClick={handleAddAttachment} >{t`添加附件`}</Button>}</span>} />
      <ResponsiveGrid gap={[0, 30]} style={{ paddingLeft: 20 }}>
        <Cell colSpan={12}>
          <TauTable
            primaryKey="orderNumber"
            size="small"
            hidePagination
            tableLayout="fixed"
            dataSource={toJS(refund?.attachments)}
            cellProps={(r) => ({ style: { cursor: 'pointer', backgroundColor: idx === r ? 'var(--color-fill1-1)' : 'unset' } })}
            columns={[
              { title: '#', dataIndex: 'idx', width: 44, cell: (_, i) => i + 1 },
              column('title', {}, orderModel?.attachments[0]),
              column('description', {}, orderModel?.attachments[0]),
              { title: t`附件个数`, dataIndex: 'cnt', width: 84, cell: (_, i, row) => <Button type="primary" text>{row.binaryId?.length}</Button> },
            ].concat(isViewMode ? [{ align: 'left', width: 30, cell: (_, i) => (i === idx && <Icon type="arrow-right" size="xs" style={{ color: 'var(--color-line1-4)' }} />) }] : [
              {
                title: <span style={{ paddingLeft: 16 }}>{t`操作`}</span>,
                dataIndex: 'title',
                align: 'left',
                width: 110,
                cell: (_, i, row) => (
                  <span>
                    <Button type="primary" text onClick={() => setCurAttachment(row)} >{t`编辑`}</Button>
                    <span>  </span>
                    <Button type="primary" text onClick={(e) => handleDeleteAttachment(i, e)} >{t`删除`}</Button>
                    {i === idx && <Icon type="arrow-right" size="xs" style={{ marginLeft: 16, color: 'var(--color-line1-4)' }} />}
                  </span>
                ),
              },
            ])}
            onRowClick={(_, index) => setIdx(index)}
          />
        </Cell>
        <Cell colSpan={5} style={{ paddingTop: 30 }}>
          {idx >= 0 && <UploadPanel
            isPreview={isViewMode}
            prefix={`partner:${refund.id}:attachment`}
            binaryIds={idx === -1 ? [] : toJS(refund.attachments[idx]?.binaryId)}
            onUploaded={(meta) => {
              refund.attachments[idx]?.binaryId.push(meta.binaryId);
            }}
            onRemove={(info) => {
              refund.attachments[idx]?.binaryId.splice(refund.attachments[idx]?.binaryId.findIndex((r) => r == info.uid), 1);
            }}
          />}
        </Cell>
      </ResponsiveGrid>
      <Dialog
        visible={!!curAttachment}
        onCancel={() => setCurAttachment(false)}
        onClose={() => setCurAttachment(false)}
        title={t`附件`}
        style={{ width: '50%' }}
        footer={null}
      >
        <AttachmentForm
          data={curAttachment}
          onSubmit={(data) => {
            _.assign(refund.attachments[idx], data);
            setCurAttachment(false);
          }}
          onCancel={() => setCurAttachment(false)}
        />
      </Dialog>
    </>
  );
});

export default observer(OrderRefund);
